package tmp;

//import static com.sun.jersey.multipart.MultiPartMediaTypes.MULTIPART_MIXED_TYPE;
//
//import java.awt.Image;
//import java.awt.Toolkit;
//import java.io.BufferedWriter;
//import java.io.File;
//import java.io.FileWriter;
//import java.io.IOException;
//import java.nio.ByteBuffer;
//import java.text.ParseException;
//import java.text.SimpleDateFormat;
//import java.util.ArrayList;
//import java.util.Arrays;
//import java.util.Date;
//import java.util.List;
//import java.util.Locale;
//import java.util.Scanner;
//
//import javax.ws.rs.Consumes;
//import javax.ws.rs.GET;
//import javax.ws.rs.POST;
//import javax.ws.rs.Path;
//import javax.ws.rs.Produces;
//import javax.ws.rs.QueryParam;
//import javax.ws.rs.core.MediaType;
//import javax.ws.rs.core.Response;
//
//import org.apache.hadoop.conf.Configuration;
//import org.apache.hadoop.hbase.HBaseConfiguration;
//import org.apache.hadoop.hbase.KeyValue;
//import org.apache.hadoop.hbase.MasterNotRunningException;
//import org.apache.hadoop.hbase.ZooKeeperConnectionException;
//import org.apache.hadoop.hbase.client.HBaseAdmin;
//import org.apache.hadoop.hbase.client.HTable;
//import org.apache.hadoop.hbase.client.Result;
//import org.apache.hadoop.hbase.client.ResultScanner;
//import org.apache.hadoop.hbase.client.Scan;
//import org.apache.hadoop.hbase.filter.BinaryComparator;
//import org.apache.hadoop.hbase.filter.CompareFilter;
//import org.apache.hadoop.hbase.filter.FamilyFilter;
//import org.apache.hadoop.hbase.filter.Filter;
//import org.apache.hadoop.hbase.filter.FilterList;
//import org.apache.hadoop.hbase.filter.QualifierFilter;
//import org.apache.hadoop.hbase.filter.RegexStringComparator;
//import org.apache.hadoop.hbase.filter.RowFilter;
//import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
//import org.apache.hadoop.hbase.util.Bytes;
//import org.springframework.stereotype.Component;
//
//
////import com.google.common.primitives.Bytes;
//import com.aad.ws.dao.MSRRconnection;
//import com.aad.ws.dto.AnalyticAvgInput;
//import com.aad.ws.dto.AnalyticAvgOutput;
//import com.msr.lot.ws.util.DateUtil;
//import com.sun.jersey.multipart.BodyPart;
//import com.sun.jersey.multipart.MultiPart;
//
//import org.rosuda.REngine.*;
//import org.rosuda.REngine.Rserve.*;
//
//@Component
//@Path("/msr")
public class MSRResourceH {

//	MSRRconnection rConnection;
//
//	@GET
//	@Path("analytic")
//	@Consumes(MediaType.APPLICATION_JSON)
//	@Produces(MediaType.APPLICATION_JSON)
//	public Response getAvgRes(
//			@QueryParam("researchId") String researchId,
//			@QueryParam("groupId") String groupId,
//			@QueryParam("srcId") String srcId,
//			@QueryParam("leafValue") String leafValue,
//			@QueryParam("leafType") String leafType,
//			@QueryParam("from") String from,
//			@QueryParam("to") String to,
//			@QueryParam("timeScale") String timeScale) throws REngineException, REXPMismatchException {
//		
//		System.out.println("MSRResource >> analytic");
//		
//		System.out.println("inputs:");
//		System.out.println(researchId);
//		System.out.println(groupId);
//		System.out.println(srcId);
//		System.out.println(leafType);
//		System.out.println(leafValue);
//
//		AnalyticAvgInput in = new AnalyticAvgInput(researchId, groupId, srcId, leafValue, leafType, getDate(from), getDate(to), timeScale);
//			
//		//Method that reads data from HBase - this is used by correlation functionality
//		AnalyticAvgOutput out = getAvg(in);
//		//double[] out = {29,30,25,27,29,30,23,22};
//		
//    	File file = new File(getRGraph("main=\"Data set\"",out));
//
//		MultiPart multiPart = new MultiPart().bodyPart(
//				new BodyPart(out, MediaType.APPLICATION_JSON_TYPE)).bodyPart(
//				new BodyPart(file, new MediaType("image", "png")));
//
//		return Response.ok(multiPart, MULTIPART_MIXED_TYPE)
//				.header("Content-Type", "application/json").build();
//	}
//	
//	@GET
//	@Path("correlation")
//	@Consumes(MediaType.APPLICATION_JSON)
//	@Produces(com.sun.jersey.multipart.MultiPartMediaTypes.MULTIPART_MIXED)
//	public Response findCorrelation(
//			@QueryParam("xResearchId") String xResearchId,
//			@QueryParam("xGroupId") String xGroupId,
//			@QueryParam("xSrcId") String xSrcId,
//			@QueryParam("xLeafValue") String xLeafValue,
//			@QueryParam("xLeafType") String xLeafType,
//			@QueryParam("yResearchId") String yResearchId,
//			@QueryParam("yGroupId") String yGroupId,
//			@QueryParam("ySrcId") String ySrcId,
//			@QueryParam("yLeafValue") String yLeafValue,
//			@QueryParam("yLeafType") String yLeafType,
//			@QueryParam("from") String from, 
//			@QueryParam("to") String to,
//			@QueryParam("timeScale") String timeScale,
//			@QueryParam("graphType") String graphType,
//			@QueryParam("model") String model) throws REngineException, REXPMismatchException {
//
//		System.out.println("============= R Processing Correlation =============");
//		System.out.println("x inputs:"+xResearchId+"/"+xGroupId+"/"+xSrcId+"/"+xLeafType+"/"+xLeafValue);
//		System.out.println("y inputs:"+yResearchId+"/"+yGroupId+"/"+ySrcId+"/"+yLeafType+"/"+yLeafValue);
//
//		//Get Avg for x
//		AnalyticAvgInput in1 = new AnalyticAvgInput(xResearchId, xGroupId, xSrcId, xLeafValue, xLeafType, getDate(from), getDate(to), timeScale);
//		double[] xReadings = getAvg(in1).getAvg();
//
//		//Get Avg for y
//		AnalyticAvgInput in2 = new AnalyticAvgInput(yResearchId, yGroupId, ySrcId, yLeafValue, yLeafType, getDate(from), getDate(to), timeScale);
//	    double[] yReadings = getAvg(in2).getAvg();
//		
//    	RConnection c = MSRRconnection.getInstance().c;
//    	
//		// OK, so the device should be fine - let's plot - replace this by any plotting code you desire ...
//		c.assign("a", xReadings);
//	    c.assign("b", yReadings);
//
//		//test
//		//c.parseAndEval("a<-c(23,23,24,24,26,27,25,22,22)");
//		//c.parseAndEval("b<-c(150,148,160,165,200,301,215,170,161)");
//		
//		File file = new File(getRGraph("main=\"Correlation\", xlab=\"Temperature\", ylab=\"Energy Consumption\"",xReadings,yReadings));
//		
//		REXP sc = c.parseAndEval("cor(a,b, method = \""+model+"\");");
//		String score = sc.asString();
//		System.out.println("cor(a,b) ="+score);
//		
//		MultiPart multiPart = new MultiPart().bodyPart(
//				new BodyPart(score, MediaType.APPLICATION_JSON_TYPE)).bodyPart(
//				new BodyPart(file, new MediaType("image", "png")));
//
//		return Response.ok(multiPart, MULTIPART_MIXED_TYPE)
//				.header("Content-Type", "application/json").build();
//	}
//	
//	@GET
//	@Path("runscript")
//	@Consumes(MediaType.APPLICATION_JSON)
//	@Produces(MediaType.APPLICATION_JSON)
//	public Response rRunScript(@QueryParam("scriptText") String scriptText)
//	{
//    	System.out.println("============= rRunScript =============");
//    	RConnection c = MSRRconnection.getInstance().c;
//    	String buffer ="";
//    	
//    	//scriptText = "a1<-c(@get::Ucl::home::41212::lights::deviceType::15/08/2013 18:00:00::16/08/2013 18:00:00::hourly@);\na2<-c(1,1,10,9,1,1,1,1,10,1,1);\ncor(a1,a2)";
//    	//scriptText = "a1<-c(@get::Ucl::home::41212::lights::deviceType::15/08/2013 18:00:00::16/08/2013 18:00:00::hourly@);\na2<-c(@get::Ucl::home::41212::lights::deviceType::12/08/2013 18:00:00::13/08/2013 18:00:00::hourly@);\ncor(a1,a2)";
//    	System.out.println(scriptText);
//    	Scanner scanner = new Scanner(scriptText);
//    	
//		while (scanner.hasNextLine()) {
//			String line = scanner.nextLine();
//			if (line.contains("@get"))
//			{
//				String stringForGet = line.substring(line.indexOf("@get::")+"@get::".length(), line.indexOf("@",line.indexOf("@get::")+"@get::".length()));
//				String split[] = stringForGet.split("::");
//				
//				String xResearchId = split[0];
//				String xGroupId = split[1];
//				String xSrcId = split[2];
//				String xLeafValue = split[3];
//				String xLeafType = split[4];
//				String from = split[5];
//				String to = split[6];
//				String timeScale = split[7];
//				
//				System.out.println(xResearchId+"/"+xGroupId+"/"+xSrcId+"/"+xLeafValue+"/"+xLeafType+"/"+getDate(from)+"/"+getDate(to)+"/"+timeScale);
//				AnalyticAvgInput in1 = new AnalyticAvgInput(xResearchId, xGroupId, xSrcId, xLeafValue, xLeafType, getDate(from), getDate(to), timeScale);
//				
//				double[] readings = getAvg(in1).getAvg();
//				//double[] readings = {12,13,14,15,17,19,20,40,100,100,100,100};
//				
//				String stringValues = Arrays.toString(readings);
//				stringValues = stringValues.substring(stringValues.indexOf("[")+1, stringValues.indexOf("]"));
//				line = line.substring(0, line.indexOf("@get"))+stringValues+line.substring(line.lastIndexOf("@")+1);
//			}
//			
//			try {
//				REXP tempR = c.parseAndEval(line);
//				buffer += line+" -> "+tempR.asString()+"\n";
//				
//			} catch (REngineException e) {
//				e.printStackTrace();
//			} catch (REXPMismatchException e) {
//				e.printStackTrace();
//			}
//		}
//		
//		System.out.println(buffer);
//		
//		return Response.status(201).header("Access-Control-Allow-Origin", "*")
//				.entity(buffer).build();
//	}
//	
//	@GET
//	@Path("findanomaly")
//	@Consumes(MediaType.APPLICATION_JSON)
//	@Produces(com.sun.jersey.multipart.MultiPartMediaTypes.MULTIPART_MIXED)
//	public Response rFindAnomaly(
//			@QueryParam("researchId") String researchId,
//			@QueryParam("groupId") String groupId,
//			@QueryParam("srcId") String srcId,
//			@QueryParam("leafValue") String leafValue,
//			@QueryParam("leafType") String leafType,
//			@QueryParam("from") String from, 
//			@QueryParam("to") String to,
//			@QueryParam("timeScale") String timeScale) throws REngineException, REXPMismatchException
//	{
//    	System.out.println("============= rFindAnomaly =============");
//    	RConnection c = MSRRconnection.getInstance().c;
//    	String buffer = null;
//    			
//		//Get Avg for y
//    	AnalyticAvgInput in = new AnalyticAvgInput(researchId, groupId, srcId, leafValue, leafType, getDate(from), getDate(to), timeScale);
//		double[] readings = getAvg(in).getAvg();
//		//double[] readings = {29,30,25,27,29,30};
//		
//		c.assign("a", readings);
//		c.parseAndEval("library(outliers)");
//		REXP temp =  c.parseAndEval("grubbs.test(a, type = 10)");
///*			System.out.println(temp.asList().at(0).asDoubles()[0]+","+temp.asList().at(0).asDoubles()[1]);
//			System.out.println(temp.asList().at(1).asString());
//			System.out.println(temp.asList().at(2).asDouble());
//			System.out.println(temp.asList().at(3).asString());
//			System.out.println(temp.asList().at(4).asString());*/
//		buffer = temp.asList().at(3).asString()+"\nG = "+temp.asList().at(0).asDoubles()[0]+",U = "+temp.asList().at(0).asDoubles()[1]+", p-value = "+temp.asList().at(2).asDouble()+"\nAlternative hypothesis : "+temp.asList().at(1).asString()+"\n";
//		System.out.println(buffer);
//    	
//    	File file = new File(getRGraph("main=\"Outlier\"",readings));
//		
//		MultiPart multiPart = new MultiPart().bodyPart(
//				new BodyPart(buffer, MediaType.APPLICATION_JSON_TYPE)).bodyPart(
//				new BodyPart(file, new MediaType("image", "png")));
//
//		return Response.ok(multiPart, MULTIPART_MIXED_TYPE)
//				.header("Content-Type", "application/json").build();
//	}
//
//	@GET
//	@Path("standardDeviation")
//	@Consumes(MediaType.APPLICATION_JSON)
//	@Produces(MediaType.APPLICATION_JSON)
//	public Response rFindStandardDeviation(
//			@QueryParam("researchId") String researchId,
//			@QueryParam("groupId") String groupId,
//			@QueryParam("srcId") String srcId,
//			@QueryParam("leafValue") String leafValue,
//			@QueryParam("leafType") String leafType,
//			@QueryParam("from") String from, 
//			@QueryParam("to") String to,
//			@QueryParam("timeScale") String timeScale) throws REngineException, REXPMismatchException
//	{
//    	System.out.println("============= rFindStandardDeviation =============");
//    	RConnection c = MSRRconnection.getInstance().c;
//		
//		//Get Avg for y
//    	AnalyticAvgInput in = new AnalyticAvgInput(researchId, groupId, srcId, leafValue, leafType, getDate(from), getDate(to), timeScale);
//		double[] readings = getAvg(in).getAvg();
//		//double[] readings = {1,1,10,2,1,1,1,1,1,1,1,1,1,1,1,1};
//		
//		double returnValue = standardDeviation(readings,0);
//		System.out.println("standardDeviation = "+returnValue);
//    	
//    	File file = new File(getRGraph("main=\"Standard Deviation\"",readings));
//		
//		MultiPart multiPart = new MultiPart().bodyPart(
//				new BodyPart("standardDeviation = "+returnValue, MediaType.APPLICATION_JSON_TYPE)).bodyPart(
//				new BodyPart(file, new MediaType("image", "png")));
//
//		return Response.ok(multiPart, MULTIPART_MIXED_TYPE)
//				.header("Content-Type", "application/json").build();
//	}
//	
//	public static double standardDeviation(double[] array, int option) {
//	    if (array.length < 2) 
//	    	return Double.NaN;
//
//	    double sum = 0.0;
//	    double sd = 0.0;
//	    double diff;
//	    double meanValue = mean(array);
//
//	    for (int i = 0; i < array.length; i++) {
//	      diff = array[i] - meanValue;
//	      sum += diff * diff;
//	    }
//	    sd = Math.sqrt(sum / (array.length - option));
//
//	    return sd;
//	  }
//	
//	public static double mean(double[] array) {
//	    double sum = 0.0;
//
//	    for (int i = 0; i < array.length; i++)
//	      sum += array[i];
//
//	    return sum / array.length;
//	  }
//	
//	public String getRGraph(String option, double[]... dataset) throws REngineException, REXPMismatchException {
//		System.out.println("============= get R Graph =============");
//		
//    	String device = "png"; // device we'll call (this would work with pretty much any bitmap device)
//    	RConnection c = MSRRconnection.getInstance().c;
//    	
//    	REXP xp = c.parseAndEval(device+"('dataset.png')");
//
//    	if (xp.inherits("try-error")) { // if the result is of the class try-error then there was a problem
//    		System.err.println("Can't open "+device+" graphics device:\n"+xp.asString());
//    		// this is analogous to 'warnings', but for us it's sufficient to get just the 1st warning
//    		REXP w = c.eval("if (exists('last.warning') && length(last.warning)>0) names(last.warning)[1] else 0");
//    		if (w.isString()) 
//    			System.err.println(w.asString());
//    	}
//    	
//    	if(dataset.length == 1)
//    	{
//    		c.assign("y", dataset[0]);
//    		c.parseAndEval("plot(y,"+option+");");
//    	}
//    	else if(dataset.length == 2)
//    	{
//    		c.assign("x", dataset[0]);
//    		c.assign("y", dataset[1]);
//    		c.parseAndEval("plot(x,y,"+option+");");
//    	}
//		
//		c.parseAndEval("dev.off();");
//		
//		String path = "C:/Program Files/R/R-3.0.1/bin/i386/dataset.png";
//		return path;
//	}
//
//	public Date getDate(String dateString)
//	{
//		Date returnDate = null;
//		try {
//			returnDate = new SimpleDateFormat("dd/MM/yyyy hh:mm").parse(dateString);
//		} catch (ParseException e) {
//			e.printStackTrace();
//		}	
//		return returnDate;
//	}
//
//	private static AnalyticAvgOutput getAvg(AnalyticAvgInput input) {
//
//		// TODO:George add code to query hbase
//		// dummy data for now
////		AnalyticAvgOutput out = new AnalyticAvgOutput();
////		double avg[] = { 109.9f, 12.1f, 64.3f, 4.1f, 112.4f, 123.9f, 12.4f,
////				0.1f, 0f, 400f, 123.3f };
////		out.setAvg(avg);
////		return out;
//		
//		AnalyticAvgOutput out = new AnalyticAvgOutput();
//		
//		
//		// Check if the HBase is available
////		try {
////			
////			 HBaseAdmin.checkHBaseAvailable(hBaseMsrAPI.getConf());
////			
////		} catch (MasterNotRunningException e1) {
////				e1.printStackTrace();
////				System.out.println(e1.toString());
////		} catch (ZooKeeperConnectionException e1) {
////				e1.printStackTrace();
////				System.out.println(e1.toString());
////		}
//
//
////			// Date From converting
////			Date dateFrom = null;
////			try {
////				dateFrom = new SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.ENGLISH).parse(input.getFrom().toString());
////			} catch (ParseException e1) {
////				// TODO Auto-generated catch block
////				e1.printStackTrace();
////			}
//		
//			String dateFromStr = String.valueOf(input.getFrom().getTime());
//			dateFromStr = DateUtil.makeFixedLength(dateFromStr);
//			System.out.println("The date From in miliseconds is : " + dateFromStr);
//			
////			// Date To converting
////			Date dateTo = input.getTo();
////			try {
////				dateTo = new SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.ENGLISH).parse(to);
////			} catch (ParseException e1) {
////				// TODO Auto-generated catch block
////				e1.printStackTrace();
////			}
//			
//			
//			String dateToStr = String.valueOf(input.getTo().getTime());
//			dateToStr = DateUtil.makeFixedLength(dateToStr);
//			System.out.println("The date To in miliseconds is : " + dateToStr);
//			
//			
//			StringBuilder strBuilder = new StringBuilder();
//			
//			strBuilder.append(input.getResearchId());
//			strBuilder.append("/");
//			strBuilder.append(input.getGroupId());
//			strBuilder.append("/");
//			strBuilder.append(input.getSrcId());
//			strBuilder.append("/");
//			strBuilder.append(input.getLeafValue());
//			
//			System.out.println("Printing the Stinrg Builder value: " + strBuilder);
//			
//			// convert Builder string to a string
//			String rowStr = strBuilder.toString();
//			
//			// Create a list of filters to be applied 	
//			List<Filter> filters = new ArrayList<Filter>();
//			
//			//filtering RowKey
//			Filter rowFilter = new RowFilter(CompareFilter.CompareOp.EQUAL,
//					new RegexStringComparator(rowStr));
//			filters.add(rowFilter);
//								
//			
//			//filtering FamilyColumn
//			Filter familyFilter = new FamilyFilter(CompareFilter.CompareOp.EQUAL,
//					new RegexStringComparator(input.getTimeScale()));
//			filters.add(familyFilter);
//			
//			//filtering qualifier "from" time range
//			Filter qualifierFilterFrom = new QualifierFilter(CompareOp.GREATER_OR_EQUAL, 
//					new BinaryComparator(dateFromStr.getBytes()));
//			filters.add(qualifierFilterFrom);
//			
//			//filtering qualifier "to" time range
//			Filter qualifierFilterTo = new QualifierFilter(CompareOp.LESS_OR_EQUAL, 
//					new BinaryComparator(dateToStr.getBytes()));
//			filters.add(qualifierFilterTo);
//			
//			
//			FilterList filterList = new FilterList(FilterList.Operator.MUST_PASS_ALL,filters);
//		
//			try {
//				HTable table = new HTable(hBaseMsrAPI.getConf(), "lotAnalyticsTest2");
//				//table.setAutoFlush(true);
//				Scan scan = new Scan();
//				scan.setFilter(filterList);
//				ResultScanner scanner = table.getScanner(scan);
//				for (Result result : scanner) {
//					for (KeyValue kv : result.raw()) {
//						System.out.print(new String(kv.getRow()) + " ");
//						System.out.print(new String(kv.getFamily()) + ":");
//						System.out.print(new String(kv.getQualifier()) + " ");
//						//System.out.print(kv.getTimestamp() + " ");
//						System.out.println(new String(kv.getValue()));
//						
//						//out.setAvg(ByteBuffer.wrap(kv.getValue()).getDouble() );
//						ByteBuffer byteBuffer = ByteBuffer.wrap(kv.getValue(), kv.getValueOffset(), kv.getValue().length);
//						out.setAvg(byteBuffer.asDoubleBuffer().array());
//								
//					}
//					
//				}
//				
//				scanner.close();
//				table.close();
//				
//				
//			} catch (IOException e) {
//				
//				e.printStackTrace();
//				System.out.println(e.toString());
//			}
//			return out;
//			
//
//		
//	
//			
//		
//	}
//	
//	
//	private static AnalyticAvgOutput getAvgDevices(AnalyticAvgInput input){
//		
//		AnalyticAvgOutput out = new AnalyticAvgOutput();
//		
//		
//		return out;
//		
//	}
//
//	@GET
//	@Path("devices")
//	@Produces(MediaType.APPLICATION_JSON)
//	public Response getAppsForCategory() {
//		System.out.println("MSRResource >> devices ");
//
//		MSRDevices col = new MSRDevices();
//		List<DeviceComparison> lst = new ArrayList<DeviceComparison>();
//
//		DeviceComparison dev1 = new DeviceComparison("Lighting", 227.03f,
//				"April 1, 2012");
//		DeviceComparison dev2 = new DeviceComparison("Furnace", 34.98f,
//				"April 1, 2012");
//		DeviceComparison dev3 = new DeviceComparison("Air Conditioning",
//				10.87f, "April 1, 2012");
//		DeviceComparison dev4 = new DeviceComparison("Smoke Alarms", 6.01f,
//				"April 1, 2012");
//		DeviceComparison dev5 = new DeviceComparison("Television", 59.02f,
//				"April 1, 2012");
//		DeviceComparison dev6 = new DeviceComparison("Microsave", 01.03f,
//				"April 1, 2012");
//		lst.add(dev1);
//		lst.add(dev2);
//		lst.add(dev3);
//		lst.add(dev4);
//		lst.add(dev5);
//		lst.add(dev6);
//		col.setDeviceDetails(lst);
//		// return appsCol;
//		return Response.status(201).header("Access-Control-Allow-Origin", "*")
//				.entity(col).build();
//	}
//
//	@GET
//	@Path("door")
//	@Produces(MediaType.APPLICATION_JSON)
//	public Response getDoorMotion() {
//		System.out.println("MSRResource >> door motion ");
//
//		MSRDoorMotionAnalysisResult col = new MSRDoorMotionAnalysisResult();
//		List<DoorMotion> lst = new ArrayList<DoorMotion>();
//		DoorMotion dev1 = new DoorMotion(2, 10, "12");
//		DoorMotion dev2 = new DoorMotion(32, 0, "13");
//		DoorMotion dev3 = new DoorMotion(1, 1, "14");
//		DoorMotion dev4 = new DoorMotion(1, 10, "15");
//		DoorMotion dev5 = new DoorMotion(8, 20, "15");
//
//		lst.add(dev1);
//		lst.add(dev2);
//		lst.add(dev3);
//		lst.add(dev4);
//		lst.add(dev5);
//		col.setDoorMotionResults(lst);
//		// return appsCol;
//		return Response.status(201).header("Access-Control-Allow-Origin", "*")
//				.entity(col).build();
//	}
//
//	@POST
//	@Path("door")
//	@Produces(MediaType.APPLICATION_JSON)
//	@Consumes(MediaType.APPLICATION_JSON)
//	public Response StoreInDB(MSRDoorMotionAnalysisRequest req)
//			throws InvalidAttribute {
//		System.out.println("******************* "
//				+ "Request recieved to write data : " + req
//				+ " ******************* ");
//
//		// validate request
//		File file = new File("door_data.txt");
//
//		// if file doesnt exists, then create it
//		if (!file.exists()) {
//			try {
//				file.createNewFile();
//				System.out.println("Creates new file!!!!!!");
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
//
//		try {
//
//			for (DoorMotionDetector detector : req.getDoorMotion()) {
//
//				String content = detector.getRecordTime() + '\t'
//						+ detector.getLocation() + '\t' + detector.getStatus();
//				System.out.println("Writing to file --------" + content);
//				// MSR1Util.writeToFS(detector.getRecordTime() + '\t' +
//				// detector.getLocation() + '\t' + detector.getStatus());
//				FileWriter fw = new FileWriter(file, true);
//				// fw = new FileWriter(file.getName());
//				BufferedWriter bw = new BufferedWriter(fw);
//				bw.append(content);
//				bw.newLine();
//				bw.close();
//			}
//
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//
//		return Response.status(201).header("Access-Control-Allow-Origin", "*")
//				.entity(req).build();
//	}
//
//
//
//
//public static void main(String[] agrs) {
//	
//	AnalyticAvgInput in = new AnalyticAvgInput("UCL", "home", "765566", "lights", "deviceType", new Date(11/12/2003), new Date(12/12/2003), "hourly");
//	
//	AnalyticAvgOutput out = getAvg(in);
//	
//	System.out.println("Printing the result : "+ out);
//	
//	
//	
//	
//}


}